﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
namespace Web.Views.Shared
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Membership.DeleteUser("agent");
            
            if(!Page.IsPostBack)
                FormsAuthentication.SignOut();
            
        }

        protected void ImgbtnLogin_Click(object sender, ImageClickEventArgs e)
        {
            
            string userName = txtUserName.Value.Trim();
            string password = txtPassword.Value.Trim();
            //如果用户名和密码为空 则返回 不做任何处理
            if (userName == "" || password == "")
            {
                txtMsg.InnerText = "请输入完整的用户名和密码.";
                
                return;
            }
            if (Membership.ValidateUser(userName, password))
            {
                MembershipUser userObj = Membership.GetUser(Context.User.Identity.Name);
                string[] roles = Roles.GetRolesForUser(userName);
                string userRoles="";
                foreach (string item in roles)
                {
                    userRoles += item+",";                   
                }
                FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(120), false, userRoles.TrimEnd(new char[]{','}), "/");
                string HashTicket = FormsAuthentication.Encrypt(Ticket);
                HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);
                Response.Cookies.Add(UserCookie);
                if (Context.Request["ReturnUrl"] != null)
                {
                    if (userRoles.Contains("Agents"))
                    {
                        //初始化代理商信息
                        (new Easydp.Controllers.AgentController()).InitAgentInfo(userName);
                    }
                    Response.Redirect(Context.Request["ReturnUrl"]);
                }
                else
                {
                    string url="~/Views/Common/default.aspx";
                    if (userRoles.Contains("Admins"))
                    {
                        url = "~/Views/Admin/ManagerUser.aspx";
                    }
                    else if (userRoles.Contains("Agents"))
                    {
                        //初始化代理商信息
                        //(new Easydp.Controllers.AgentController()).InitAgentInfo(userName);
                        url = "~/Views/AgentManager/Default.aspx";
                    }
                    Response.Redirect(url);
                }

            }
            else
            {
                txtMsg.InnerText = "用户名和密码不匹配.请重新输入.";
            }
        }

        
    }
}
